package com.share.device.emqx.factory.impl;

import com.share.device.emqx.annotation.GuiguEmqx;
import com.share.device.emqx.factory.MessageHandlerFactory;
import com.share.device.emqx.handler.MessageHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Handler工厂实现类，处理自定义注解的逻辑
 * @author zxl
 * @date 2025年03月28日 22:32
 */
@Service
public class MessageHandlerFactoryImpl implements MessageHandlerFactory, ApplicationContextAware {
    private Map<String, MessageHandler> handlerMap = new HashMap<>();
    @Override
    public MessageHandler getMessageHandler(String topic) {
        return handlerMap.get(topic);
    }

    /**
     * 初始化bean对象
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取对象
        Map<String, MessageHandler> beanMap = applicationContext.getBeansOfType(MessageHandler.class);
        for (MessageHandler messageHandler : beanMap.values()) {
            // 参数1：AnnotatedElement element  注解所在的类（接口），这里传入的messageHandler.getClass()是一个Class类，Class类实现了AnnotatedElement接口
            // 参数2：Class<A> annotationType   注解类型
            GuiguEmqx guiguEmqx = AnnotatedElementUtils.findAllMergedAnnotations(
                    messageHandler.getClass(),
                    GuiguEmqx.class).iterator().next();
            if (null != guiguEmqx) {
                String topic = guiguEmqx.topic();
                // 初始化到map
                handlerMap.put(topic, messageHandler);
            }
        }
    }
}
